<template>
    <div class="params">
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 提示框 -->
            <el-alert
                title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                show-icon
                :closable="false">
            </el-alert>
            <!--选择商品分类区-->
            <el-row class="cat_opt">
                <el-col >
                    <span>选择商品分类:</span>
                    <!-- 选择商品分类的级联选择框-->
                     <el-cascader
                        class="cascader"
                        v-model="selectvalue"
                        :options="cateList"
                        :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children' }"
                        @change="handleChange">
                    </el-cascader>
                </el-col>
            </el-row>
            <!-- tabs 标签页-->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many" >
                    <el-button class="iptadd" size="mini" type="primary" :disabled="isbtndisable" @click="addparamsdialogVisible=true">添加参数</el-button> 
                    <el-table :data="manytabledata" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag @close="closetag(i,scope.row)" closable v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editparams(scope.row)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteparams(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>   
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button class="iptadd" @click="addparamsdialogVisible=true" size="mini" type="primary" :disabled="isbtndisable">添加属性</el-button>
                    <el-table :data="onlytabledata" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag @close="closetag(i,scope.row)" closable v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editparams(scope.row)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteparams(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加动态/静态属性 -->
        <el-dialog
            :title="'添加'+titleText"
            :visible.sync="addparamsdialogVisible"
            width="30%"
            @close="closeaddparams">
            <el-form :model="addparamsruleForm" :rules="addparamsrules" ref="addparamsref" label-width="100px" >
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addparamsruleForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addparamsdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addparamssure">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改的对话款 -->
        <el-dialog
            :title="'修改'+titleText"
            :visible.sync="editparamsdialogVisible"
            width="30%">
            <el-form :model="editparamsruleForm" :rules="editparamsrules" ref="editparamsref" label-width="100px" >
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editparamsruleForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editparamsdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editparamssure">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            cateList:[],//商品分类数据
            selectvalue:[],//选中的级联选择框中的数据
            activeName:"many",//被激活的tabs名称
            manytabledata:[],//动态参数数据
            onlytabledata:[],//静态参数数据
            addparamsdialogVisible:false,//静态/动态参数弹出框的显示与隐藏
            editparamsdialogVisible:false,//修改弹出框的显示与隐藏
            addparamsruleForm:{
                attr_name:""
            },
            editparamsruleForm:{
                attr_name:""
            },
            addparamsrules:{
                attr_name:[
                    { required: true, message: '请输入属性或参数名称', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
                ]
            },
            editparamsrules:{
                attr_name:[
                    { required: true, message: '请输入属性或参数名称', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
                ]
            }
        }
    },
    created(){
        //获取所以商品分类数据
        this.getcateList()
    },
    computed:{
        //控制添加属性和参数的禁用
        isbtndisable(){
            return this.selectvalue.length!==3
        },
        //当前选中的三级分类id
        cardId(){
            if(this.selectvalue.length === 3)
            return this.selectvalue[2]
            return null
        },
        //动态决定添加弹出框的是添加动态还是静态属性
        titleText(){
            if(this.activeName == 'many')
            return '动态参数'
            else
            return '静态属性'
        }
    },
    methods:{
        //获取所以商品分类数据
        async getcateList(){
            const {data:res} = await this.$http.get('categories')
            if(res.meta.status!=200) return this.$message.error("获取商品分类数据失败")
            this.cateList =res.data
            console.log(this.cateList)
        },
        //处理联级选择器选择事件
        handleChange(){
            if(this.selectvalue.length!=3)
            {
                this.selectvalue=[]
                this.manytabledata = []
                this.onlytabledata = []
                return
            }
            this.getparamsdata()

        },
        //发起请求后去属性和参数数据
        async  getparamsdata(){
            const {data:res} = await this.$http.get(`categories/${this.cardId}/attributes`,{
                params:{sel:this.activeName}
            })
            if(res.meta.status!=200) return this.$message.error("获取参数数据失败")
            res.data.forEach(item=>{
                item.attr_vals = item.attr_vals? item.attr_vals.split(' '):[]
                //控制文本框的显示
                item.inputVisible =false
                //文本框输入的值
                item.inputValue = ''

            })
            console.log(res.data)
            if(this.activeName == 'many')
            this.manytabledata = res.data
            this.onlytabledata = res.data
        },
        //tabs点击处理函数
        handleClick(){
            if(this.selectvalue.length!=3) return
            this.getparamsdata()
        },
        //关闭添加属性和参数弹出框
        closeaddparams(){
            this.$refs.addparamsref.resetFields()
        },
        //点击了添加弹出框中确定按钮的处理函数
        addparamssure(){
            //预验证
            this.$refs.addparamsref.validate(async valid=>{
                if(!valid) return
                //发起请求添加属性
                const {data:res} = await this.$http.post(`categories/${this.cardId}/attributes`,{
                    attr_name:this.addparamsruleForm.attr_name,
                    attr_sel:this.activeName
                })
                if(res.meta.status!=201) return this.$message.error("添加失败")
                this.getparamsdata()
                this.addparamsdialogVisible = false
                return this.$message.success("添加成功")
            })
        },
        //点击了修改弹出框中确定按钮的处理函数
        editparamssure(){
              this.$refs.editparamsref.validate(async valid=>{
                if(!valid) return
                //发起请求添加属性
                const {data:res} = await this.$http.put(`categories/${this.cardId}/attributes/${this.editparamsruleForm.attr_id}`,{
                    attr_name:this.editparamsruleForm.attr_name,
                    attr_sel:this.activeName
                })
                if(res.meta.status!=200) return this.$message.error("修改失败")
                this.getparamsdata()
                this.editparamsdialogVisible = false
                return this.$message.success("修改成功")
            })
        },
        //点击了编辑按钮
        async editparams(row){
            //查询当前参数的信息
            const {data:res} = await this.$http.get(`categories/${this.cardId}/attributes/${row.attr_id}`,{
                params:{attr_sel:this.activeName}
            })
            if(res.meta.status!=200) return this.$message.error("获取参数信息失败")
            this.editparamsruleForm = res.data
            this.editparamsdialogVisible = true
            
        },
        //点击了删除处理函数
        async deleteparams(row){
            const resinfo = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
             }).catch(err=>err)
             if(resinfo!='confirm') return this.$message.info("您取消了本次操作")
            const {data:res} = await this.$http.delete(`categories/${this.cardId}/attributes/${row.attr_id}`)
            if(res.meta.status!=200) return this.$message.error("删除该参数失败")
            this.getparamsdata()
            return this.$message.success("删除该参数成功")
        },
        //可编辑的tag处理函数
         handleInputConfirm(row){
            if(row.inputValue.trim().length==0) {
                row.inputValue = ''
                row.inputVisible = false
                return
            }
            row.attr_vals.push(row.inputValue.trim())
            this.savetag(row)
            return
            
        },
        //保存tag
        async savetag(row){
            const {data:res} = await this.$http.put(`categories/${this.cardId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:row.attr_sel,
                attr_vals:row.attr_vals.join(' ')
            })
            if(res.meta.status!=200) return this.$message.error("添加属性失败")
            this.$message.success("修改属性成功")
            row.inputValue = ''
            row.inputVisible =false
            return
        },
        //tag输入函数
        showInput(row){
            row.inputVisible = true
            //文本框自动获取焦点
            this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        //删除tag
        closetag(i,row){
             row.attr_vals.splice(i,1)
            this.savetag(row)
        }
    }
}
</script>

<style scoped>
.cat_opt{
    margin-top: 15px;
}
.cascader{
    margin-left: 10px;
    width: 400px;
}
.iptadd{
    margin-bottom: 10px;
}
.el-tag{
    margin: 10px;
}
.input-new-tag{
    width: 120px;
}
</style>